package deployr.core;

import java.io.*;
import java.util.*;

public class Metadata {

	private final Map<String, String> map = new HashMap<String, String>();

	public Metadata(InputStream metadataStream) {
		Scanner scanner = scanning(metadataStream);
		while (scanner.hasNext()) {
			map(scanner.next());
		}
	}

	private Scanner scanning(InputStream metadataStream) {
		return new Scanner(metadataStream).useDelimiter("\n");
	}

	private void map(String string) {
		map(keyOf(string), valuesOf(string));
	}

	private String keyOf(String string) {
		return string.replaceAll(":.*$", "");
	}

	private void map(String key, String value) {
		map.put(key, value);
	}

	private String valuesOf(String next){
		return next.substring(next.indexOf(":") + 1);
	}

	public boolean projectKeyIs(String projectKey) {
		return new AppId(get("projectKey")).equals(new AppId(projectKey));
	}

	public String get(String key) {
		return map.get(key);
	}

	public boolean updateKeyIs(String updateKey) {
		if (!relatedToUpdate()) return false;
		return get("updateKey").equals(updateKey);
	}

	private boolean contains(String string) {
		return map.containsKey(string);
	}

	public boolean relatedToUpdate() {
		return contains("updateKey");
	}

	public boolean relatedToProject() {
		return contains("projectKey") && !relatedToUpdate();
	}

}
